package org.ouwh.fw.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

public class Util {
	private Util() {
	}

	public static Properties loadProperties(String filepath) throws Exception {
		Properties props = new Properties();
		FileInputStream in = null;
		try {
			in = new FileInputStream(filepath);
			props.load(in);
			return props;
		} finally {
			try {
				in.close();
			} catch (Exception e) {
			}
		}
	}

	public static void storeProperties(String filepath, Properties props)
			throws Exception {
		FileOutputStream out = null;
		FileLock lock = null;
		MyProperties myProps = new MyProperties(props);
		FileInputStream in = null;
		try {
			in = new FileInputStream(filepath);
			myProps.loadKeys(in);
		} finally {
			try {
				in.close();
			} catch (Exception e) {
			}
		}
		try {
			out = new FileOutputStream(filepath);
			FileChannel channel = out.getChannel();
			lock = channel.tryLock();
			if (lock != null) {
				SimpleDateFormat format = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss.SSS");
				Date date = new Date();
				myProps.store(out, "Last edit time: " + format.format(date));
			} else {
				throw new Exception("file is being edited: " + filepath);
			}
		} finally {
			try {
				out.close();
			} catch (Exception e) {
			}
			try {
				lock.release();
			} catch (Exception e) {
			}
		}
	}
	
	public static void storeProperties2(String filepath, Properties props, String key)
			throws Exception {
		FileOutputStream out = null;
		FileLock lock = null;
		MyProperties myProps = new MyProperties(props);
		FileInputStream in = null;
		try {
			in = new FileInputStream(filepath);
			myProps.loadKeys(in);
			if (!myProps.isContainKey(key)) {
				myProps.addKey(key);
			}			
		} finally {
			try {
				in.close();
			} catch (Exception e) {
			}
		}
		try {
			out = new FileOutputStream(filepath);
			FileChannel channel = out.getChannel();
			lock = channel.tryLock();
			if (lock != null) {
				SimpleDateFormat format = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss.SSS");
				Date date = new Date();
				myProps.store(out, "Last edit time: " + format.format(date));
				
			} else {
				throw new Exception("file is being edited: " + filepath);
			}
		} finally {
			try {
				out.close();
			} catch (Exception e) {
			}
			try {
				lock.release();
			} catch (Exception e) {
			}
		}
	}	
	
}
